package com.sharemedia.views
{
	import com.sharemedia.events.TrackEvent;
	import com.sharemedia.events.TrackListEvent;
	import com.sharemedia.interfaces.IAudioManager;
	import com.sharemedia.managers.db.AddTracksCommand;
	import com.sharemedia.managers.db.LoadTracksCommand;
	import com.sharemedia.managers.db.TrackDataBase;
	import com.sharemedia.managers.db.UpdateRatingCommand;
	import com.sharemedia.vos.ServerTrack;
	import com.sharemedia.vos.Track;
	
	import flash.data.SQLConnection;
	import flash.events.Event;
	import flash.events.FileListEvent;
	import flash.events.MouseEvent;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;
	import flash.net.FileFilter;
	
	import mx.utils.UIDUtil;

	public class ServerPlayList extends Playlist
	{
		private var dataBase:TrackDataBase = TrackDataBase.getInstance();
		public function ServerPlayList()
		{
			super();
		}
		
		override public function set audioManager(value:IAudioManager):void
		{
			super.audioManager = value;
			
			var loadTracksComnmand:LoadTracksCommand = new LoadTracksCommand();
			loadTracksComnmand.addEventListener(TrackListEvent.LOADED, tracksLoadedhandler);
			dataBase.execute(loadTracksComnmand);
		}
		
		override protected function doubleClickHandler(event:MouseEvent):void
		{
			if(list && list.selectedItem && audioManager.connected)
			{
				audioManager.play(list.selectedItem);
			}
		}
		
		override protected function addTrackHandler(event:MouseEvent):void
		{
			super.addTrackHandler(event);
			
			var file:File = new File();
			file.addEventListener(FileListEvent.SELECT_MULTIPLE, file_selectMultiple);
			file.browseForOpenMultiple("Please select a files",[new FileFilter("MP3", "*.mp3")]);
		}
		
		private function file_selectMultiple(event:FileListEvent):void 
		{
			var tracks:Array = new Array();
				
			for each (var file:File in event.files) 
			{
				var track:ServerTrack = new ServerTrack(UIDUtil.createUID(), file.name, file.nativePath);
				track.loadID3(dataBase);
				audioManager.trackList.addTrack(track);
				tracks.push(track);
			}
			
			dataBase.execute(new AddTracksCommand(tracks));
		}
		
		protected function tracksLoadedhandler(event:TrackListEvent):void
		{
			for each (var track:ServerTrack in event.tracks) 
			{
				//track.loadID3();
				audioManager.trackList.addTrack(track);
			}
		}
		
		override protected function playHandler(event:TrackEvent):void
		{
			if(list)
				list.selectedItem = audioManager.currentTrack;
		}
	}
}